package com.xyj.zjbz.task;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.logging.Logger;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.xyj.zjbz.constants.Constants;
import com.xyj.zjbz.po.ZJDataSource;
import com.xyj.zjbz.user.service.UserService;
import com.xyj.zjbz.util.DynamicDataSource;
import com.xyj.zjbz.util.DynamicLoadBean;
import com.xyj.zjbz.util.MySqlUtil;
import com.xyj.zjbz.util.XMLUtils;
import com.xyj.zjbz.vo.MysqlUrl;

@Component("mySQLBackUpTask")
public class MySQLBackUpTask {
	@Autowired
	private Constants c;
	@Autowired
	UserService userService;
	@Autowired
	DynamicLoadBean loadBean;
	@Autowired
	DynamicDataSource dataSources;
	@Autowired
	ApplicationContext context;
	private static Logger log = Logger.getLogger(MySQLBackUpTask.class
			.getName());

	/**
	 * cron表达式：* * * * * *（共6位，使用空格隔开，具体如下） cron表达式：*(秒0-59) *(分钟0-59) *(小时0-23)
	 * *(日期1-31) *(月份1-12或是JAN-DEC) *(星期1-7或是SUN-SAT)
	 * 
	 * @throws IOException
	 */
	@Scheduled(cron = "0 13 10 * * *")
	public void toBackUp() {
		// 文件夹不存在，则创建文件夹
		SimpleDateFormat sim = new SimpleDateFormat("MM/dd/");
		String date = sim.format(new Date());
		String filePath = c.getBackupPath() + date;
		File file = new File(filePath);
		if (!file.exists()) {
			log.info("指定路径不存在，正在创建路径。。");
			file.mkdirs();
		}
		List<ZJDataSource> bzlist = userService.getBZSystem();
		for (ZJDataSource bz : bzlist) {
			MysqlUrl mysqlurl = new MysqlUrl(c.getMysqlAdminUser(),
					c.getMysqlAdminPwd(), c.getMysqlIp(), c.getMysqlPort(),
					bz.getBzDB());
			String time = new SimpleDateFormat("HH-mm").format(new Date());
			String path = filePath + bz.getBzDB() + "-" + time + ".sql";
			try {
				MySqlUtil.backupDb(mysqlurl, path);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		log.info("数据库备份完毕....");
	}

	/**
	 * 加载datasource（单位毫秒） 启动时执行一次，然后间隔8小时执行一次
	 */
	@Scheduled(fixedRate = 60 * 1000 * 60 * 8)
	public void loadDataSources() {
		log.info("初始化加载已经存在的datasource....");
		// 获得所有的datasources
		String path = MySQLBackUpTask.class.getClassLoader()
				.getResource("dynamic").getPath();
		List<ZJDataSource> bzlist = userService.getBZSystem();
		for (ZJDataSource bz : bzlist) {
			File f = new File(path + bz.getBzDB() + ".xml");
			if (!f.exists()) {
				XMLUtils.createXMLByTemp(bz);
				log.info("dynamic/" + bz.getBzDB() + ".xml 创建完成。。");
			}
			// 加载bean
			loadBean.loadBean("classpath:dynamic/" + bz.getBzDB() + ".xml");
			Object ds = context.getBean(bz.getBzDB());
			// 添加dataSource
			dataSources.addDataSource(bz.getBzDB(), ds);
		}
	}
}
